
import sys
import imp
import time
import threading

class RecvThread(threading.Thread):
	def __init__(self, cap):
		threading.Thread.__init__(self)
		self.m_cap = cap
		self.m_should_kill = False

	def kill(self):
		print "Kill command on thread"
		self.m_should_kill = True

	def _handler(self, cap, pkt, context):
		if self.m_should_kill:
			return False
		
		print "PKT", cap, pkt, context

		return True

	def run(self):
		print "Sniffing..."
		self.m_cap.loop(self._handler, self)

try:
	pywinpcap = imp.load_dynamic("pywinpcap", sys.argv[1])
	sys.modules["pywinpcap"] = pywinpcap

	print "Test Script:"

	print dir(pywinpcap)

	devices = pywinpcap.find_all_devices()

	cap = pywinpcap.Capture(devices[0])

	print cap
	print cap.device
	
	thread = RecvThread(cap)
	thread.start()

	try:
		while True:
			print "1 Sec..."
			time.sleep(1)
				# cap.send("\0" * 50)
				# pkt = cap.next()
				# print x, repr(pkt), pkt.timestamp()
	except KeyboardInterrupt:
		print "Goodbye"
	finally:
		thread.kill()
		thread.join()
		print "Thread is dead.."

except Exception, e:
	print "Error:", e
finally:
	sys.stdin.readline()
